<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <image src="@/static/返回箭头.png" class="back-icon" @tap="goBack"></image>
      <text class="nav-title">个人信息</text>
    </view>

    <!-- 头像区域 -->
    <view class="avatar-section" @tap="chooseAvatar">
      <image :src="userInfo.userPhoto || '/static/default-avatar.png'" class="avatar" mode="aspectFill"></image>
      <view class="camera-icon">
        <uni-icons type="camera" size="20" color="#fff"></uni-icons>
      </view>
    </view>

    <!-- 信息列表 -->
    <view class="info-list">
      <view class="info-item">
        <text class="item-label">用户名</text>
        <input
            type="text"
            v-model="userInfo.username"
            placeholder="请输入用户名"
            class="item-input"
        />
      </view>

      <view class="info-item">
        <text class="item-label">邮箱</text>
        <input
            type="text"
            v-model="userInfo.email"
            placeholder="请输入邮箱"
            class="item-input"
        />
      </view>

      <view class="info-item">
        <text class="item-label">密码</text>
        <view class="item-value">
          <text>********</text>
          <text class="action-text" @tap="changePassword">修改</text>
        </view>
      </view>

      <view class="divider"></view>

      <view class="info-item">
        <text class="item-label">性别</text>
        <picker @change="bindGenderChange" :value="genderIndex" :range="genders">
          <view class="picker-value">
            {{ genders[genderIndex] }}
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </picker>
      </view>

      <view class="info-item">
        <text class="item-label">年龄</text>
        <input
            type="number"
            v-model="userInfo.age"
            placeholder="请输入年龄"
            class="item-input"
        />
      </view>

      <view class="info-item">
        <text class="item-label">爱好</text>
        <input
            type="text"
            v-model="userInfo.resume"
            placeholder="请输入爱好"
            class="item-input"
        />
      </view>
    </view>

    <!-- 按钮区域 -->
    <view class="button-group">
      <button class="btn save-btn" @tap="saveProfile">保存修改</button>
      <button class="btn logout-btn" @tap="logout">退出登录</button>
    </view>
  </view>
</template>

<script>
import {api} from '@/utils/request.js'

export default {
  data() {
    return {
      userInfo: {
        username: '',
        email: '',
        userPhoto: '',
        sex: '男',
        age: '',
        resume: ''
      },
      genders: ['男', '女'],
      genderIndex: 0,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      isLoading: false
    }
  },
  onLoad() {
    this.loadUserProfile()
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    async loadUserProfile() {
      try {
        uni.showLoading({title: '加载中...'})
        const res = await api.getUserProfile()
        uni.hideLoading()

        if (res.code === 200 && res.result) {
          // await this.loadUserProfile()
          // 处理头像数据
          let userData = res.result

          // 如果头像是base64格式但没有前缀，添加前缀
          if (userData.avatar && !userData.avatar.startsWith('data:image')) {
            if (userData.avatar.startsWith('http')) {
              // 如果是URL格式，保持不变
            } else {
              // 假设是base64格式，添加前缀
              userData.avatar = `data:image/jpeg;base64,${userData.avatar}`
            }
          }

          this.userInfo = {
            ...this.userInfo,
            ...userData
          }

          // 设置性别索引
          const genderIndex = this.genders.findIndex(g => g === this.userInfo.sex)
          this.genderIndex = genderIndex >= 0 ? genderIndex : 0
        } else {
          uni.showToast({
            title: '获取个人信息失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '获取个人信息失败',
          icon: 'none'
        })
        console.error('获取个人信息出错:', error)
      }
    },
    readFileAsBase64(filePath) {
      return new Promise((resolve, reject) => {
        // H5 方案：使用 FileReader
        uni.request({
          url: filePath,
          method: 'GET',
          responseType: 'arraybuffer',
          success: (res) => {
            const blob = new Blob([res.data], {type: 'image/jpeg'});
            const reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = () => resolve(reader.result);
          },
          fail: reject
        });

        // App 方案：使用 Base64 编码
        // #ifdef APP-PLUS
        plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
          entry.file((file) => {
            const reader = new plus.io.FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = (evt) => resolve(evt.target.result);
          }, reject);
        }, reject);
        // #endif
      });
    },
    async chooseAvatar() {
      // 定义统一的用户信息更新方法

// 选择图片并上传逻辑
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['camera', 'album'],
        success: async (res) => {
          try {
            const tempFilePath = res.tempFilePaths[0];
            this.imgurl = tempFilePath; // 预览图片
            this.$forceUpdate();

            // ---------- 核心：跨平台读取 Base64 ----------
            const base64Data = await this.readFileAsBase64(tempFilePath);

            // 调用更新接口
            const response = await api.updateUserProfile({
              userPhoto: base64Data // 字段名根据接口调整
            });
            if (response.code === 200) {
              await this.loadUserProfile()
            }
            uni.showToast({title: '更新成功', icon: 'success'});

          } catch (error) {
            console.error('上传失败', error);
            uni.showToast({title: '上传失败，请重试', icon: 'none'});
          }
        },
        fail: (err) => {
          console.log('取消选择', err);
          uni.showToast({title: '未选择图片', icon: 'none'});
        }
      });
    },

    getBase64FromImagePath(filePath) {
      return new Promise((resolve, reject) => {
        uni.getFileSystemManager().readFile({
          filePath: filePath,
          encoding: 'base64',
          success: (res) => {
            const base64 = `data:image/png;base64,${res.data}`; // 确保 Base64 格式正确
            resolve(base64);
          },
          fail: (err) => {
            console.error('读取图片失败:', err);
            reject(err);
          }
        });
      });
    },
    bindGenderChange(e) {
      this.genderIndex = e.detail.value
      this.userInfo.sex = this.genders[this.genderIndex]
    },
    changePassword() {
      // 重置密码表单
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      uni.showModal({
        title: '输入新密码',
        placeholderText: '请输入新密码（至少6个字符）',
        editable: true,
        success: (res) => {
          if (res.confirm && res.content) {
            if (res.content.length < 6) {
              return uni.showToast({title: '密码长度至少为6个字符', icon: 'none'});
            }
            this.passwordForm.newPassword = res.content;
            // 添加 setTimeout
            setTimeout(() => {
              uni.showModal({
                title: '确认新密码',
                placeholderText: '请再次输入新密码',
                editable: true,
                success: (res2) => {
                  if (res2.confirm && res2.content) {
                    // 验证两次密码是否一致
                    if (res2.content !== this.passwordForm.newPassword) {
                      return uni.showToast({
                        title: '两次输入的密码不一致',
                        icon: 'none'
                      })
                    }

                    this.passwordForm.confirmPassword = res2.content

                    // 调用修改密码的API
                    this.confirmChangePassword(this.passwordForm.newPassword, this.passwordForm.confirmPassword)
                  }
                }
              });
            }, 0);
          }
        }
      });

    },

    async confirmChangePassword(password, confirmPassword) {
      const res = await api.updateUserProfile({
        "password": password,
        "confirmPassword": confirmPassword
      })
      if (res.code == 200) {
        uni.showToast({
          title: '修改密码成功',
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: '修改密码失败',
          icon: 'error'
        })
      }
    },
    async saveProfile() {
      try {
        if (this.isLoading) return
        this.isLoading = true

        // 验证必填字段
        if (!this.userInfo.username) {
          uni.showToast({
            title: '请输入用户名',
            icon: 'none'
          })
          this.isLoading = false
          return
        }

        if (!this.userInfo.email) {
          uni.showToast({
            title: '请输入邮箱',
            icon: 'none'
          })
          this.isLoading = false
          return
        }

        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        if (!emailRegex.test(this.userInfo.email)) {
          uni.showToast({
            title: '邮箱格式不正确',
            icon: 'none'
          })
          this.isLoading = false
          return
        }

        uni.showLoading({title: '保存中...'})

        // 处理头像数据
        let avatar = this.userInfo.avatar

        // 如果头像是base64格式且包含前缀，移除前缀
        if (avatar && avatar.startsWith('data:image')) {
          // 只在需要时移除前缀，取决于后端API的要求
          // 有些API需要完整的data:image/jpeg;base64,前缀，有些只需要base64编码部分
          // 这里假设后端需要完整的base64字符串（包含前缀）
        }

        const updateData = {
          username: this.userInfo.username,
          email: this.userInfo.email,
          sex: this.userInfo.sex,
          age: this.userInfo.age ? parseInt(this.userInfo.age) : null,
          resume: this.userInfo.resume
          // avatar: avatar // 包含头像数据
        }

        const res = await api.updateUserProfile(updateData)

        uni.hideLoading()
        this.isLoading = false

        if (res.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: res.message || '保存失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        this.isLoading = false
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
        console.error('保存个人信息出错:', error)
      }
    },
    async logout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({title: '退出中...'})
              await api.logout()
              uni.hideLoading()

              // 清除本地存储的用户信息和token
              uni.removeStorageSync('token')
              uni.removeStorageSync('userInfo')

              // 跳转到登录页
              uni.reLaunch({
                url: '/pages/login/login'
              })
            } catch (error) {
              uni.hideLoading()
              uni.showToast({
                title: '退出失败',
                icon: 'none'
              })
              console.error('退出登录出错:', error)
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f8f9fc;
  padding-bottom: 40rpx;
}

.nav-bar {
  background: #fff;
  height: 88rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  position: relative;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .back-icon {
    width: 40rpx;
    height: 40rpx;
  }

  .nav-title {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    font-size: 34rpx;
    font-weight: 500;
    color: #333;
  }
}

.avatar-section {
  background: linear-gradient(135deg, #4a90e2, #6ab5ff);
  padding: 60rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;

  .avatar {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    border: 4rpx solid rgba(255, 255, 255, 0.8);
    background: #f5f5f5;
  }

  .camera-icon {
    position: absolute;
    bottom: 60rpx;
    right: 50%;
    transform: translateX(40rpx);
    width: 50rpx;
    height: 50rpx;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
  }
}

.info-list {
  background: #fff;
  margin: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;

  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .item-label {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }

    .item-value {
      font-size: 28rpx;
      color: #666;
      display: flex;
      align-items: center;
      gap: 20rpx;
    }

    .item-input {
      font-size: 28rpx;
      color: #333;
      text-align: right;
      width: 400rpx;
    }

    .action-text {
      color: #4a90e2;
      font-size: 28rpx;
    }

    .picker-value {
      font-size: 28rpx;
      color: #333;
      display: flex;
      align-items: center;
      gap: 10rpx;
    }
  }

  .divider {
    height: 20rpx;
    background: #f8f9fc;
  }
}

.button-group {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;

  .btn {
    height: 90rpx;
    border-radius: 45rpx;
    width: 70%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: 500;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

    &.save-btn {
      background: #4a90e2;
      color: #fff;

      &:active {
        background: #3a80d2;
      }
    }

    &.logout-btn {
      background: #fff;
      color: #ff5252;
      border: 1rpx solid #ff5252;

      &:active {
        background: #fff5f5;
      }
    }
  }
}
</style> 